//! Windows Live Messenger Library
//! Copyright (c) Microsoft Corporation. All rights reserved.
//! http://dev.live.com/messenger
//
// <reference path="sscorlib.js" />
// <reference path="Microsoft.Live.Messenger.documentation.js" />

function onLoad()
{
    // Create Sign-in control
	var ctl = new Microsoft.Live.Messenger.UI.SignInControl(
	    "SignInControl", 
	    "http://www.contoso.com/privacy.htm", 
	    "http://www.contoso.com/channel.htm", 
	    "en-us"
	    );
	// Attach authenticated completed event handler
	ctl.add_authenticationCompleted(onAuthenticated);
}


/// Global variable to hold Messenger user object
var user;

function onAuthenticated(sender, e)
{
    // Create a user object
    user = new Microsoft.Live.Messenger.User(e.get_identity());
    user.add_signInCompleted(onSignedIn);
    // Sign in user
    user.signIn();
}

function onSignedIn(sender, e)
{
	if (e.get_resultCode() == 0)
	{
	    alert("Sign In Succeeded");
    
    	// Add contact list
	    populateContactList();
             
        // Handler for all new conversations
        user.get_conversations().add_collectionChanged(onConversationCollectionChanged);

        // Show UI
        document.getElementById("Client").style.display = "block";
	}
	else
	{
		alert("Sign in failed");
	}
}

/// Set personal message
function onSetPersonalMessage()
{
    var message = document.getElementById("PersonalMessageInput").value;
    user.get_presence().set_personalMessage(message);
}

/// Populate contact list
function populateContactList()
{
    // Get contact list container element
	var contactListElement = document.getElementById("ContactList");
    var contactElement;
    var contacts = user.get_contacts();
    // Iterate through contact collection
	var enumerator = contacts.getEnumerator();
    while (enumerator.moveNext()) 
    {
        contact = enumerator.get_current();
        contactElement = createContactElement(contact);
        contactListElement.appendChild(contactElement);
    }
}

function createContactElement(contact)
{
    // Create contact container element
    var contactElement = document.createElement("div");
    contactElement.setAttribute("className", "ContactItem");
    // Create text span elements for contact presence properties
    var displayNameElement = document.createElement("span");
    var statusElement = document.createElement("span");
    var personalMessageElement = document.createElement("span");
    contactElement.appendChild(displayNameElement);
    contactElement.appendChild(statusElement);
    contactElement.appendChild(personalMessageElement); 
    contactElement.attachEvent("ondblclick", createOnContactDblClick(contact));
        
    // Display contact presence
    var address = contact.get_currentAddress();
    displayDisplayName("", address.get_address(), displayNameElement);
    displayStatus(address.get_presence().get_status(), statusElement);      

    // Add contact presence update event handler
    addOnContactPresenceUpdated(
        contact,
        displayNameElement,
        statusElement,
        personalMessageElement
        );
        
    return contactElement;        
}     

function addOnContactPresenceUpdated(
    contact,
    displayNameElement,
    statusElement,
    personalMessageElement
    )
{
    contact.get_currentAddress().get_presence().add_propertyChanged(
        // Create anonymous event handler function for presence property updates
        function(sender, e) {
            var address = contact.get_currentAddress();
            var presence = address.get_presence();
            switch (e.get_propertyName())
            {
            case "Status":
                displayStatus(presence.get_status(), statusElement);
                break;
            case "DisplayName":
                displayDisplayName(presence.get_displayName(), address.get_address(), displayNameElement);
                break;
            case "PersonalMessage":
                displayPersonalMessage(presence.get_personalMessage(), personalMessageElement);
                break;
            default:
                break;
            }
            return true;
       }
   );
}

function displayStatus(status, element)
{
    switch (status)
    {
    case Microsoft.Live.Messenger.PresenceStatus.offline: 
        element.innerText = " (Offline) ";
        break;
    case Microsoft.Live.Messenger.PresenceStatus.away: 
        element.innerText = " (Away) ";
        break;
    default: 
        element.innerText = " (Online) "; 
        break;  
    }
}

function displayDisplayName(name, address, element)
{
    element.innerText = name == "" ? address : name;
}

function displayPersonalMessage(message, element)
{
    element.innerText = message == "" ? message : " - " + message;
}

function createOnContactDblClick(contact)
{
    return function() {
        var address = contact.get_currentAddress();
        if (address.get_isOnline())
            return user.get_conversations().create(address);
        else
            return null;
    }   
}

function onConversationCollectionChanged(sender, e)
{
    if (e.get_action() == Microsoft.Live.Core.NotifyCollectionChangedAction.add)
    {
        var items = e.get_newItems();
        var start = e.get_newStartingIndex();
        for (i = 0; i < items.length; i++)
        {
            createConversationElement(items[i]);
        }    
    }
    else
    {
        /* Not important for conversation collections */
    }
}

function createConversationElement(conversation)
{
    // Create a conversation DOM
    var conversationElement = document.createElement("div");
    conversationElement.setAttribute("className", "ConversationItem");
    var conversationHistory = document.createElement("div");
    conversationHistory.setAttribute("className", "ConversationHistory");
    var conversationArea = document.createElement("textarea");
    conversationArea.setAttribute("className", "ConversationArea");
    var conversationInput = document.createElement("input");
    conversationInput.setAttribute("className", "ConversationInput");
    conversationInput.setAttribute("type", "submit");
    conversationInput.setAttribute("value", "Send");
    conversationElement.appendChild(conversationHistory);
    conversationElement.appendChild(conversationArea);
    conversationElement.appendChild(conversationInput);
   
    // Attach send message handler to input event
    conversationInput.attachEvent("onclick", createOnMessageSend(conversation, conversationArea, conversationHistory));
    
    // Attach receive message handler for this conversation
    conversation.add_messageReceived(createOnMessageReceived(conversationHistory));

    // Add to conversation list and display it
    var conversations = document.getElementById("Conversations");    
    conversations.appendChild(conversationElement);
    conversations.appendChild(document.createElement("br"));
}

function createOnMessageSend(conversation, conversationArea, conversationHistory)
{
    return function() {
        var message = new Microsoft.Live.Messenger.TextMessage(conversationArea.value);
        conversation.sendMessage(message);
        displayMessage(message, conversationHistory);
        conversationArea.value = "";
    };
}

function createOnMessageReceived(conversationHistory)
{
    return function(sender, e) {
        var message = e.get_message();
        if (message.get_type() === Microsoft.Live.Messenger.MessageType.textMessage)
        {
            displayMessage(message, conversationHistory);
        }
        return true;
    };
}

function displayMessage(message, conversationHistory)
{
    // Create message block DOM
    var messageElement = document.createElement("div");
    messageElement.setAttribute("className", "MessageBlock");
    var attributionElement = document.createElement("span");
    var says = document.createTextNode(" says:");
    var breakElement = document.createElement("br");

    // Insert the message data
    attributionElement.innerText = message.get_sender().get_presence().get_displayName();
    var textElement = message.createTextElement();
    textElement.setAttribute("className", "TextMessage")
    
    messageElement.appendChild(attributionElement);
    messageElement.appendChild(says);
    messageElement.appendChild(breakElement);
    messageElement.appendChild(textElement);
    
    // Add to history
    conversationHistory.appendChild(messageElement);
}
